<template>
  <div>
    <div v-if="showAdd" class="filter-container">
      <el-button-group style="float: right">
        <el-button type="primary" class="filter-item" @click="addFileView">添加附件</el-button>
      </el-button-group>
    </div>
    <el-table
      :data="fileList"
      border
      style="width: 100%"
    >
      <el-table-column label="序号" type="index" min-width="5%" />
      <el-table-column v-if="showCol.indexOf('orderCode') > -1" prop="orderCode" label="审批单编号" min-width="20%" />
      <el-table-column v-if="showCol.indexOf('supplierName') > -1" prop="supplierName" label="供应商名称" min-width="20%" />
      <el-table-column v-if="showCol.indexOf('contractCode') > -1" prop="contractCode" label="审批单编号" min-width="20%" />
      <el-table-column prop="fileName" label="文件名称" min-width="20%" />
      <el-table-column prop="fileSize" label="文件大小" min-width="15%" />
      <el-table-column prop="fileType" label="文件类型" min-width="15%" />
      <el-table-column prop="fileComment" label="备注" min-width="20%" />
      <el-table-column label="操作" min-width="15%">
        <template slot-scope="{row}">
          <el-button-group style="float: left;">
            <el-button v-show="canPreview(row.fileType)" type="text" style="margin-right: 5px" @click.native="previewFile(row.id, row.fileType)">预览</el-button>
            <el-button type="text" style="margin-right: 5px" @click.native="downloadFile(row)">下载</el-button>
            <el-button type="text" style="margin-right: 5px" @click.native="updateFile(row)">修改</el-button>
            <el-button v-permission="'purchase:file:delete'" type="text" @click.native="btnDeleteFile(row.id)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0 && showPage"
      :total="total"
      :current.sync="queryParam.current"
      :size.sync="queryParam.size"
      @pagination="getlistFile"
    />
    <preview-file ref="previewFileRef" :url="preViewFileUrl" :file-type="previewFileType" />

    <add-file ref="addDialogRef" :add-file-dto="mountParam" @handleChild="handleChild" />

    <el-dialog title="修改文件" :append-to-body="true" :visible.sync="dialogUpdateFormVisible" width="50%" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="110px">
        <el-form-item label="文件名称" prop="fileName"><el-input v-model="temp.fileName" /></el-form-item>
        <el-form-item label="备注" prop="fileComment"><el-input v-model="temp.fileComment" /></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="dialogUpdateFormVisible = false">取消</el-button>
        <el-button icon="el-icon-check" type="primary" @click="updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { getFileAction, deleteAction, getAction, putAction } from '@/api/manage'
import { Message } from 'element-ui'
import previewFile from '@/views/purchase/previewFile/index'
import Pagination from '@/components/Pagination'
import addFile from '@/views/purchase/file/components/addFile'

export default {
  name: '',
  components: {
    previewFile,
    Pagination,
    addFile
  },
  props: {
    queryFileParam: {
      type: Object
    },
    showCol: {
      type: Array,
      required: false,
      default: function() {
        return []
      }
    },
    showPage: {
      type: Boolean,
      default: false
    },
    showAdd: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      total: 0,
      preViewFileUrl: '',
      previewFileType: 'img',
      fileList: [],
      queryParam: {
        current: 1,
        size: 10,
        orderId: '',
        projectId: '',
        supplierId: '',
        contractId: '',
        fileName: undefined,
        fileType: undefined
      },
      temp: {},
      dialogUpdateFormVisible: false,
      rules: {
        fileName: [{
          required: true,
          message: '文件名称不能为空',
          trigger: 'change'
        }]
      }
    }
  },
  computed: {
    mountParam: function() {
      var { orderId, projectId, supplierId, contractId } = this.queryFileParam
      return { orderId, projectId, supplierId, contractId }
    }
  },
  created() {
    this.getlistFile()
  },
  methods: {
    canPreview(fileType) {
      return fileType === 'jpg' || fileType === 'jpeg' || fileType === 'png' || fileType === 'pdf'
    },
    btnDeleteFile(fileId) {
      deleteAction('/purchase/file/delete/', { ids: fileId }).then(
        ({ msg }) => {
          Message.success(msg)
          this.getlistFile()
        })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          putAction('/purchase/file/update', this.temp).then(({ msg }) => {
            this.dialogUpdateFormVisible = false
            Message.success(msg)
            this.getlistFile()
          })
        }
      })
    },
    updateFile(row) {
      console.log(row.fileName)
      this.temp = Object.assign({}, row)
      this.dialogUpdateFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    addFileView() {
      this.$refs.addDialogRef.show()
    },
    handleChild(data) {
      const fns = {
        addFileComplete() {
          this.getlistFile()
        }
      }
      return fns[data.type] && fns[data.type].call(this)
    },
    downloadFile(row) {
      const fileId = row.id
      const fileName = row.fileName
      const fileType = row.fileType
      getFileAction('/purchase/file/download/' + fileId).then(res => {
        if (res.type === 'application/json') {
          const reader = new FileReader() // 创建读取文件对象
          reader.addEventListener('loadend', function() { //
            const resJson = JSON.parse(reader.result) // 返回的数据
            Message.error(resJson.msg)
          })
          reader.readAsText(res, 'utf-8') // 设置读取的数据以及返回的数据类型为utf-8
        } else {
          const doca = window.document.createElement('a')
          const url = window.URL.createObjectURL(res)

          doca.href = url
          doca.setAttribute('download', fileName + '.' + fileType)
          window.document.body.appendChild(doca)
          doca.click()
          window.document.body.removeChild(doca)
          window.URL.revokeObjectURL(url)
        }
      })
    },
    previewFile(fileId, fileType) {
      getFileAction('/purchase/file/preview/' + fileId).then(res => {
        const blobUrl = window.URL.createObjectURL(res)
        this.preViewFileUrl = blobUrl
        this.previewFileType = this.getPreviewFileType(fileType)
        this.$refs.previewFileRef.show()
      })
    },
    getPreviewFileType(fileType) {
      switch (fileType) {
        case 'png':
          return 'img'
        case 'jpg':
          return 'img'
        case 'jpeg':
          return 'img'
        case 'pdf':
          return 'pdf'
        default:
          return 'img'
      }
    },
    getlistFile() {
      const param = Object.assign(this.queryParam, this.queryFileParam)
      if (!this.showPage) {
        // 清空 current siz
        param.current = null
        param.size = null
      }
      getAction('/purchase/file/list', param).then(
        res => {
          const { data } = res
          this.fileList = data.records
          this.total = data.total
        }
      )
    }
  }
}
</script>
